import {_decorator, Button, instantiate, Label, Node, Prefab, Vec2} from 'cc';
import UCard from '../components/UCard';
import {ClickEventType} from '../GameDef';
import {BaseCard} from '../models/Card';
import {ManagerBase} from './ManagerBase';


const {ccclass, property} = _decorator;

@ccclass('StorageManager')
export default class StorageManager extends ManagerBase {
    cardsBuffer: BaseCard[] = [];

    @property(Prefab)
    cardPrefab: Prefab = null;

    @property(Node)
    storageNode: Node = null;

    @property(Node)
    additionalMark: Node = null;

    latticeLimit: number = 10;

    get uCards(): UCard[] {
        return this.storageNode.children.map(node => node.getComponent(UCard));
    }

    onLoad() {
    }

    onDestroy() {
    }

    addCard(CardData: BaseCard) {
        this.cardsBuffer.push(CardData);

        return [this.storageNode, new Vec2(0, 0)]
    }

    refreshUI() {
        this.storageNode.removeAllChildren();
        for(let cardData of this.cardsBuffer) {
            let cardNode = instantiate(this.cardPrefab);
            let card     = cardNode.getComponent(UCard);
            card.init(0, this.uCards.length, ClickEventType.STORAGE);
            card.refresh(cardData);
            card.isOpen                            = true;
            card.getComponent(Button).interactable = false;
            this.storageNode.addChild(cardNode);
        }
    }

    checkGameOver(){
        return this.cardsBuffer.length >= this.latticeLimit;
    }
    getStorage() {
        return this.cardsBuffer;
    }

    getUCardByUid(cardUid: number) {
        return this.uCards.find(card => card.uid == cardUid);
    }

    initUI() {
        this.storageNode.removeAllChildren();
        this.checkAdditionalMark()
    }

    initData() {
        this.cardsBuffer = [];
    }

    removeCardByUid(cardUid: number) {
        let cardData = this.cardsBuffer.find(card => card.uid == cardUid);
        if (!cardData) {
            return;
        }
        this.cardsBuffer = this.cardsBuffer.filter(card => {
            return card.uid != cardUid;
        });
        this.checkAdditionalMark();

        let cardUI = this.uCards.find(card => card.uid == cardUid);
        if (!cardUI) {
            return;
        }
        cardUI.node.removeFromParent();

        this.checkAdditionalMark();
    }

    moveOut() {
        for(let CardUI of this.uCards) {
            CardUI.node.removeFromParent()
        }
        this.checkAdditionalMark()
    }

    private checkAdditionalMark() {

        this.additionalMark.active = this.uCards.length != this.cardsBuffer.length;
        let label = this.additionalMark.getComponentInChildren(Label);
        label.string = String(this.cardsBuffer.length - this.uCards.length)
    }
}